<script setup>
import { Edit, Delete } from "@element-plus/icons-vue";
import { ref } from "vue";
const categorys = ref([
  {
    id: "",
    name: "",
  },
]);

//声明一个异步的函数
import {
  bookClassifyListService,
  bookClassifyByNameService,
  bookClassifyAddService,
  bookClassifyUpdateService,
  bookClassifyDeleteService
} from "@/api/books.js";
const bookClassifyList = async () => {
  let result = await bookClassifyListService();
  categorys.value = result.data;
};
bookClassifyList();

//控制添加分类弹窗
const dialogVisible = ref(false);

//添加分类数据模型
const categoryModel = ref({
  id: "",
  name: "",
});
const is = ref(true)
//自定义确认密码的校验函数
const isDisable = (rule, value, callback) => {
    if (value == null || value === '') {
        is.value=true
        callback(new Error('请输入分类名称'))
    }
    else{
        is.value=false
        callback()
    }
}
//添加分类表单校验
const rules = {
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" },
  {max: 10, message: '长度不超过10位非空字符', trigger: 'blur'},
  { validator: isDisable, trigger: 'change' }],
  
};

//定义变量，控制标题的展示
const title = ref("");

// const data = ref([
//   {
//     id:"",
//     name: ""
//   },
// ]);
//调用接口，添加表单
import { ElMessage, ElMessageBox } from "element-plus";
const addCategory = async () => {
  let result1 = await bookClassifyByNameService(categoryModel.value);
  // data.value = result1.data;
  if (result1.data != "") {
    ElMessage.error("该图书类名已存在");
    // alert(data.value)
    return;
  }

  //调用接口
  let result = await bookClassifyAddService(categoryModel.value);
  ElMessage.success(result.msg ? result.msg : "添加成功");

  //调用获取所有文章分类的函数
  bookClassifyList();

  dialogVisible.value = false;
};

//展示编辑弹窗
const showDialog = (row) => {
  dialogVisible.value = true;
  title.value = "修改分类";
  //数据拷贝
  categoryModel.value.name = row.name;
  //扩展id属性，将来需要传递给后台
  categoryModel.value.id = row.id;
};

//修改分类
const updateCategory = async () => {
  let result1 = await bookClassifyByNameService(categoryModel.value);
  if (result1.data != "") {
    ElMessage.error("该图书类名已存在");
    return;
  }

  //调用接口
  let result = await bookClassifyUpdateService(categoryModel.value);

  ElMessage.success(result.msg ? result.msg : "修改成功");

  //调用获取所有分类的函数
  bookClassifyList();

  //隐藏弹窗
  dialogVisible.value = false;
};

//清空模型的数据
const clearDate = () => {
  categoryModel.value.name = "";
};

//删除分类
const deleteClassify = (row)=>{
  //提示用户 确认框

  ElMessageBox.confirm(
    '是否确认删除该分类?',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //调用接口
      let result = await bookClassifyDeleteService(row.id);

      ElMessage({
        type: 'success',
        message: '删除成功',
      })

      //刷新列表
      bookClassifyList();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })

}

</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>文章分类</span>
        <div class="extra">
          <el-button
            type="primary"
            @click="
              dialogVisible = true;
              title = '添加分类';
              clearDate();
            "
            >添加分类</el-button
          >
        </div>
      </div>
    </template>

    <el-table :data="categorys" style="width: 100%">
      <el-table-column label="序号" width="400" type="index"> </el-table-column>
      <el-table-column
        label="分类名称"
        width="400"
        prop="name"
      ></el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button :icon="Edit" type="primary" @click="showDialog(row)"
            >修改</el-button
          >
          <el-button :icon="Delete" type="danger" @click="deleteClassify(row)">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 添加分类弹窗 -->
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="categoryModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryModel.name"
            minlength="1"
            maxlength="10"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="title == '添加分类' ? addCategory() : updateCategory()"
            :disabled=is
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
  align-items: center;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>